//
//  WQWkViewController.m
//  CloudRecipes
//
//  Created by 程杰 on 2022/5/18.
//

#import "WQWkViewController.h"
#import <WebKit/WebKit.h>
#import "WQWeakWebViewScriptMessageDelegate.h"


//竖屏幕宽高
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)



@interface WQWkViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic,strong) WKWebView *wkWebView;
@end

@implementation WQWkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.view addSubview:self.wkWebView];

}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([message.name isEqualToString:@"setCloudMenuCommands"]) {
        NSString *info = [NSString stringWithFormat:@"%@",message.body];
        [self showMsg:info];
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
 
    NSLog(@"---finidsh---");
}

- (void)showMsg:(NSString *)msg {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"我接收H5的内容" message:msg?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    
        [self.wkWebView evaluateJavaScript:@"getCloudMenuInfos('这是我回传的内容：天气很好啊！')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            NSLog(@"--response--%@",response);
        }];
        
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
    
}

// 在这里可以新开另一个wkwebview
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration");
    
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


//-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
//{
//    //如果是跳转一个新页面
//    if (navigationAction.targetFrame == nil) {
//        [webView loadRequest:navigationAction.request];
//    }
//
//    decisionHandler(WKNavigationActionPolicyAllow);
//}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"message is %@", message);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"HTML的弹出框" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (WKWebView *)wkWebView {
    
    if (_wkWebView == nil) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        WKPreferences *preference = [[WKPreferences alloc]init];
        preference.minimumFontSize = 0;
        preference.javaScriptEnabled = YES;
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preference;
        
        config.allowsInlineMediaPlayback = YES;
        config.mediaTypesRequiringUserActionForPlayback = YES;
        config.allowsPictureInPictureMediaPlayback = YES;
        
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WQWeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WQWeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"setCloudMenuCommands"];
        
        config.userContentController = wkUController;
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:config];
        _wkWebView.backgroundColor = [UIColor whiteColor];
        _wkWebView.UIDelegate = self;
        _wkWebView.navigationDelegate = self;
        _wkWebView.allowsBackForwardNavigationGestures = YES;
       
//        NSString *path = [[NSBundle mainBundle] pathForResource:@"854/854_index.html" ofType:nil];
//        NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//        [_wkWebView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
        
        [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://dev.51miaomiao.cn/open-cloud-iot-statics/iotShare/devices/iotControl.html?accessKey=ml001&Authorization=bearer%2093ceef328c67e7ed87da839aa184f67c"]]];
        
    }
    return _wkWebView;
}

@end
